// store/modules/supplies.js

import { fetchSupplies, createSupply, updateSupply, deleteSupply } from '@/api/supplies';

const state = {
  supplies: [],
  loading: false,
  error: null,
  
};

const mutations = {
  SET_SUPPLIES(state, supplies) {
    state.supplies = supplies;
  },
  SET_LOADING(state, status) {
    state.loading = status;
  },
  SET_ERROR(state, error) {
    state.error = error;
  },
};

const actions = {
  fetchSupplies({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_LOADING', true);
      commit('SET_ERROR', null);
      fetchSupplies().then(response => {
        console.log('获取物资信息成功:', response.data);
        commit('SET_SUPPLIES', response.data);
        resolve(response); // 可以选择是否需要解析响应
      })
        .catch(error => {
          console.error('获取物资信息失败:', error.message);
          commit('SET_ERROR', '加载物资信息失败，请稍后再试！');
          reject(error); // 传递错误到Promise的拒绝状态
        })
        .finally(() => {
          commit('SET_LOADING', false);
        });
    });
  },


  async createSupply({ commit, dispatch }, data) {
    return new Promise(async (resolve, reject) => {
      try {
        commit('SET_LOADING', true);
        commit('SET_ERROR', null);
        console.log(data)
        await createSupply(data.data);
        console.log('创建物资成功');
        await dispatch('fetchSupplies'); // 刷新物资列表

        resolve(); // 成功创建后解析Promise
      } catch (error) {
        console.error('创建物资失败:', error);
        commit('SET_ERROR', '创建物资失败，请稍后再试！');
        reject(error); // 创建失败后拒绝Promise
      } finally {
        commit('SET_LOADING', false);
      }
    });
  },

  async updateSupply({ commit, dispatch }, { id, data }) {
    return new Promise(async (resolve, reject) => {
      try {
        commit('SET_LOADING', true);
        commit('SET_ERROR', null);

        console.log("更新物资data：",data);
        await updateSupply(id, data);
        console.log('更新物资成功');
        await dispatch('fetchSupplies'); // 刷新物资列表

        resolve(); // 成功更新后解析Promise
      } catch (error) {
        console.error('更新物资失败:', error);
        commit('SET_ERROR', '更新物资失败，请稍后再试！');
        reject(error); // 更新失败后拒绝Promise
      } finally {
        commit('SET_LOADING', false);
      }
    });
  },

  async deleteSupply({ commit, dispatch }, id) {
    return new Promise(async (resolve, reject) => {
      try {
        commit('SET_LOADING', true);
        commit('SET_ERROR', null);

        await deleteSupply(id);
        console.log('删除物资成功');
        await dispatch('fetchSupplies'); // 刷新物资列表

        resolve(); // 成功删除后解析Promise
      } catch (error) {
        console.error('删除物资失败:', error);
        commit('SET_ERROR', '删除物资失败，请稍后再试！');
        reject(error); // 删除失败后拒绝Promise
      } finally {
        commit('SET_LOADING', false);
      }
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};